package com.ict.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.core.domain.entity.SysRole;
import com.ict.system.mapper.SysDeptMapper;
import com.ict.system.mapper.SysUserMapper;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysRoleService;
import com.ict.web.constant.Constants;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.dto.YzqFileDTO;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.Notice;
import com.ict.web.dto.InsertNoticeDto;
import com.ict.web.dto.QueryNoticeDto;
import com.ict.web.dto.UpdateNoticeDto;
import com.ict.web.mapper.NoticeMapper;
import com.ict.web.mapper.OrganizationManagementMapper;
import com.ict.web.msg.util.CreateMsgUtil;
import com.ict.web.service.INoticeService;
import com.ict.web.vo.NoticeDetailVo;
import com.ict.web.vo.NoticeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 公告Service业务层处理
 *
 * @author xss
 * @date 2022-02-15
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper,Notice> implements INoticeService
{

    @Autowired
    private NoticeMapper noticeMapper;
    @Resource
    private IYzqFileService fileService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private OrganizationManagementMapper organizationManagementMapper;
    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    /**
     * 查询公告详情
     * @param noticeId 公告
     * @return
     */
    @Override
    public NoticeDetailVo selectNoticeByNoticeId(Long noticeId) {
       Notice notice =  noticeMapper.selectByNoticeId(noticeId);
       //获取文件名字
        NoticeDetailVo noticeDetailVo = new NoticeDetailVo();
        BeanUtils.copyProperties(notice,noticeDetailVo);
        YzqFile file = fileService.getById(notice.getNoticeFile());
        noticeDetailVo.setNoticeFile(file);
       Assert.isTrue(notice != null,"数据不存在!!!");
        return noticeDetailVo;
    }

    /**
     * 查询公告列表
     * @param queryDto 公告
     * @return
     */
    @Override
    public List<NoticeVo> selectNoticeList(QueryNoticeDto queryDto) {

        return noticeMapper.selectNoticeList(queryDto);
    }

    /**
     * 发布公告信息
     * @param addDto 公告
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int releaseNotice(InsertNoticeDto addDto) {
        Notice notice = InsertNoticeDto.of(addDto);
        notice.setNoticeStatus(Notice.NOTICE_STATUS_RELEASE);
        //同步文件
        ArrayList<YzqFile> fileList = InsertNoticeDto.toFile(notice,addDto);
        fileService.batchInsertFile(fileList);
        //公告同步到消息
        ArrayList<Long> list = new ArrayList<>();
        List<String> noticeSends = Arrays.asList(addDto.getNoticeSend().split(","));
        noticeSends.forEach(s->{
            if (Long.valueOf(s).equals(Constants.ROLE_TYPE_PROJECT)) {
                //发送者为项目单位，大数据局和大数据局普通用户也需要收到消息
                List<Long> bigDateUserIds = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA);
                List<Long> bigDateNormalUserIds = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA_NORMAL);
                list.addAll(bigDateUserIds);
                list.addAll(bigDateNormalUserIds);
            }
            //根据传入角色获取对应用户
            SysRole sysRole = sysRoleService.selectRoleById(Long.valueOf(s));
            Assert.isTrue("0".equals(sysRole.getStatus()),"角色已停用，请重新选择");
            Assert.isTrue("0".equals(sysRole.getDelFlag()),"角色不存在，请重新选择");
            List<Long> userIds = userRoleMapper.getUserIdByRoleId(Long.valueOf(s));

            list.addAll(userIds);
        });
        int insert = noticeMapper.insert(notice);

        list.forEach(s->{
            CreateMsgUtil.createMsgAndNotice(addDto.getNoticeContent(),s,addDto.getNoticeTitle(),null,null,notice.getNoticeId(),notice.getNoticeFile());
        });

        return insert;
    }

    /**
     * 保存公告
     * @param addDto
     * @return
     */
    @Override
    public int saveNotice(InsertNoticeDto addDto){
        Notice notice = InsertNoticeDto.of(addDto);
        notice.setNoticeStatus(Notice.NOTICE_STATUS_NOTRELEASE);
        //同步文件
        ArrayList<YzqFile> fileList = InsertNoticeDto.toFile(notice,addDto);
        fileService.batchInsertFile(fileList);
        return noticeMapper.insert(notice);
    }

    /**
     * 修改发布公告信息
     * @param updateDto 公告
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateReleaseNotice(UpdateNoticeDto updateDto) {
        Notice notice = UpdateNoticeDto.of(updateDto);
        Notice bean = noticeMapper.selectById(updateDto.getNoticeId());
        Assert.isTrue(!bean.getNoticeStatus().equals(Notice.NOTICE_STATUS_RELEASE),"公告已发布，不能编辑!!!");
        Assert.isTrue(bean != null && !(bean.getDelFlag().equals(Notice.DELETE_STATUS_UNNORMAL)),"公告不存在!!!");
        notice.setNoticeStatus(Notice.NOTICE_STATUS_RELEASE);
        //更新文件信息
        YzqFile fileNotice = fileService.getById(bean.getNoticeFile());
        YzqFileDTO fileDTO = updateDto.getNoticeFile();
        BeanUtils.copyProperties(fileDTO,fileNotice);
        fileService.updateById(fileNotice);

        //公告同步到消息
        HashMap<Long, String> map = new HashMap<>();
        ArrayList<Long> list = new ArrayList<>();
        List<String> noticeSends = Arrays.asList(updateDto.getNoticeSend().split(","));
        noticeSends.forEach(s->{
            if (Long.valueOf(s).equals(Constants.ROLE_TYPE_PROJECT)) {
                //发送者为项目单位，大数据局和大数据局普通用户也需要收到消息
                List<Long> bigDateUserIds = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA);
                List<Long> bigDateNormalUserIds = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA_NORMAL);
                list.addAll(bigDateUserIds);
                list.addAll(bigDateNormalUserIds);
            }
            //根据传入角色获取对应用户
            SysRole sysRole = sysRoleService.selectRoleById(Long.valueOf(s));
            Assert.isTrue("0".equals(sysRole.getStatus()),"角色已停用，请重新选择");
            Assert.isTrue("0".equals(sysRole.getDelFlag()),"角色不存在，请重新选择");
            List<Long> userIds = userRoleMapper.getUserIdByRoleId(Long.valueOf(s));

            list.addAll(userIds);
        });

        int update = noticeMapper.updateById(notice);

        Notice selectByNoticeId = noticeMapper.selectByNoticeId(notice.getNoticeId());

        list.forEach(s->{
            CreateMsgUtil.createMsgAndNotice(updateDto.getNoticeContent(),s,updateDto.getNoticeTitle(),null,null,selectByNoticeId.getNoticeId(),selectByNoticeId.getNoticeFile());
        });
        return update;
    }
    /**
     * 修改保存公告信息
     * @param updateDto 公告
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveNotice(UpdateNoticeDto updateDto) {
        Notice SaveNotice = UpdateNoticeDto.of(updateDto);
        Notice bean = noticeMapper.selectById(updateDto.getNoticeId());
        Assert.isTrue(!bean.getNoticeStatus().equals(Notice.NOTICE_STATUS_RELEASE),"公告已发布，不能编辑!!!");
        Assert.isTrue(bean != null && !(bean.getDelFlag().equals(Notice.DELETE_STATUS_UNNORMAL)),"公告不存在!!!");
        SaveNotice.setNoticeStatus(Notice.NOTICE_STATUS_NOTRELEASE);
        //更新文件信息
        YzqFile fileNotice = fileService.getById(bean.getNoticeFile());
        YzqFileDTO fileDTO = updateDto.getNoticeFile();
        BeanUtils.copyProperties(fileDTO,fileNotice);
        fileService.updateById(fileNotice);
        return noticeMapper.updateById(SaveNotice);
    }


    /**
     * 删除公告信息
     * @param noticeId
     * @return
     */
    @Override
    public int deleteNoticeByNoticeId(Long noticeId) {
        Notice bean = this.getById(noticeId);
        Assert.isTrue( !bean.getNoticeStatus().equals(Notice.NOTICE_STATUS_RELEASE),"公告已发布，不能删除!!!");
        return noticeMapper.deleteByNoticeId(noticeId);
    }
}
